package com.gomcarter.frameworks.redis;

import com.gomcarter.frameworks.base.common.BeanRegistrationUtils;
import com.gomcarter.frameworks.redis.factory.RedisFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.util.HashMap;
import java.util.NoSuchElementException;

/**
 * @author  gomcarter on 2019-11-09 23:31:48
 */
@Order
public class RedisRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
    private RedisProperties redisProperties;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata,
                                        BeanDefinitionRegistry registry) {
        // 注入redis
        BeanRegistrationUtils.registerBeanDefinitionIfNotExists(registry, "redisProxy",
                RedisFactory.class, new HashMap<String, Object>(1, 1) {{
                    put("redisProperties", redisProperties);
                }});

        // 注入切面
        BeanRegistrationUtils.registerBeanDefinitionIfNotExists(registry, "redisConfiguration", RedisConfiguration.class);
    }

    @Override
    public void setEnvironment(Environment environment) {
        try {
            redisProperties = Binder.get(environment).bind("yfcloud.frameworks.redis", RedisProperties.class).get();
        } catch (NoSuchElementException e) {
            redisProperties = new RedisProperties();
        }
    }
}
